//
//  YJPCycleView.m
//  轮播图封装(CollectionView版本)
//
//  Created by dllo on 16/5/26.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "YJPCycleView.h"
#import "YJPCycleViewCell.h"
#import "UIImageView+AFNetworking.h"
#import "WFCarouselModel.h"

#define SECTION_COUNT 1000
@interface YJPCycleView ()<UICollectionViewDataSource, UICollectionViewDelegate, UIScrollViewDelegate>

/** 数据源数组 */
@property (nonatomic, strong) NSArray *dataSourceArray;
/** 定时器时间间隔 */
@property (nonatomic, assign) CGFloat timeInterval;
/** 定时器对象 */
@property (nonatomic, strong) NSTimer *cycleTimer;
/** 当前item的下标 */
@property (nonatomic, assign) NSInteger itemIndex;
/** 当前section的下标 */
@property (nonatomic, assign) NSInteger currentSection;



@property (nonatomic, retain) NSMutableArray *carouseCachesArray;
@end

@implementation YJPCycleView

-(instancetype)initWithFrame:(CGRect)frame DataSource:(NSArray *)dataSource TimeInterval:(CGFloat)time cachesData:(NSMutableArray *)cacherArray{
//    self.carouseCachesArray = cacherArray;
    
    self = [super initWithFrame:frame];
    if (self) {
         /** 将外界传递进来的数据源赋值给dataSourceArray */
        self.dataSourceArray = dataSource;
//        NSLog(@"datasource: %@", self.dataSourceArray);
//        NSLog(@"cachArray: %@", cacherArray);
        /** 初始化默认瀑布流样式 */
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = frame.size;
        layout.minimumInteritemSpacing = 0;
        layout.minimumLineSpacing = 0;
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
        self.collectionView = [[UICollectionView alloc] initWithFrame:frame collectionViewLayout:layout];
        self.collectionView.dataSource = self;
        self.collectionView.delegate = self;
        [self addSubview:_collectionView];
        self.collectionView.pagingEnabled = YES;
        self.collectionView.showsHorizontalScrollIndicator = NO;
        
        // 设置初始偏移量
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:SECTION_COUNT / 2] atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
        /** 注册cell */
        [self.collectionView registerClass:[YJPCycleViewCell class] forCellWithReuseIdentifier:@"YJP_Cell"];
        if (time > 0) {
            self.timeInterval = time;
            [self addTimer];
        }
        
    }
    return self;
}
#pragma mark - item的个数:
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
//    if (!self.carousStyle) {
//        return self.carouseCachesArray.count;
//    } else {
        return self.dataSourceArray.count;

//    }
}
#pragma mark - section的个数:
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return SECTION_COUNT;
}
#pragma mark - 为item赋值:
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    YJPCycleViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"YJP_Cell" forIndexPath:indexPath];
    // 记录当前的item和section:
    _itemIndex = indexPath.item;
    _currentSection = indexPath.section;
    
    // 加一个数据保护
//    NSLog(@"carouse: %d", self.carousStyle);
//    if (!self.carousStyle) {
//        NSLog(@"轮播图加载本地数据,. ");
//        NSLog(@"%@", self.carouseCachesArray);
//        cell.cycleImageView.image = self.carouseCachesArray[indexPath.item];
    
        
//    } else {
        if (self.dataSourceArray.count != 0) {
            cell.carouselModel = [self.dataSourceArray objectAtIndex:indexPath.item];
            
            
            [cell.cycleImageView setImageWithURL:[NSURL URLWithString:((WFCarouselModel *)self.dataSourceArray[indexPath.item]).imgUrl] placeholderImage:[UIImage imageNamed:@"图片加载.png"]];
        }
        // 添加循环保护:(防止到最后一个分区出现崩溃)
        if (indexPath.section == SECTION_COUNT - 1) {
            // 回到最初的起点
            [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:SECTION_COUNT / 2] atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
        }

//    }
    
    
    return cell;
}
#pragma mark - 点击item触发的方法:
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
//    NSLog(@"点击了图片:%ld", indexPath.item);
    // 命令代理人去执行代理方法:
    if (self.delegate != nil) {
        [self.delegate didClickedItemAtIndexPath:indexPath];
    }
    
    
}
#pragma mark - 添加定时器:
-(void)addTimer{
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:self.timeInterval target:self selector:@selector(changePageByTime) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    self.cycleTimer = timer;
}
#pragma mark - 移除定时器:
-(void)removeTimer{
    [self.cycleTimer invalidate];
    self.cycleTimer = nil;
}
#pragma mark - 定时器调用的方法:
-(void)changePageByTime{
    if (_itemIndex == self.dataSourceArray.count) {
        _itemIndex = 0;
        _currentSection++;
    }
    // 偏移到最新的位置(下一张)
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_itemIndex inSection:_currentSection] atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
    _itemIndex++;
}
#pragma mark - 手指开始滑动时定时器失效:
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self removeTimer];
}
#pragma mark - 手指离开定时器开启:
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [self addTimer];
}



- (NSMutableArray *)carouseCachesArray {
    if (_carouseCachesArray == nil) {
        _carouseCachesArray  = [[NSMutableArray array]retain];
    }
    return _carouseCachesArray;
}




@end
